/*
 * test_http.cpp
 *
 *  Created on: Nov 12, 2013
 *      Author: killerg
 */





#include <signal.h>

#include "share/http_s.h"
#include "share/http_c3.h"
#include "share/json/json.h"
#include "share/util.h"

static bool running = false;
static void handle_ctrl_c(int signal) {
    running = false;
}

bool test_http() {
    http_server svr;
    http_client3 cli;

    if (!svr.init("localhost", 9876)) {
        perror("http_server::init error");
        return false;
    }

    if (!cli.init()) {
        perror("http_client2::init error");
        return false;
    }

    on_signal(SIGINT, handle_ctrl_c);
    running = true;


    std::list<http_server::p_request> req_list;

    svr.handle("/", [&req_list](http_server::p_request req){
        req_list.push_back(req);
    });

    Json::Value json;
    for (int i=0; i<10; ++i) {
        json["index"] = i;
        cli.do_query("http://localhost:9876/killerg/haha", to_cstr(json), [](int http_code, const std::string& data){
            printf("code:%d body:%s\n", http_code, data.c_str());
        });
    }

    while (running) {
        while (!req_list.empty()) {
            auto req = req_list.back();
            req_list.pop_back();
            const char* rep = fmt_cstr("from:%s, url:%s body:%s\n", req->ip.c_str(), req->path.c_str(), req->body.c_str());
            req->send_reply(HTTP_OK, rep);
        }

        svr.update();
        cli.update();
    }

    cli.destroy();

    svr.destroy();

    return true;
}


#include <unistd.h>

bool test_http_client2() {
    http_client3 cli;

    if (!cli.init()) {
        perror("http_client2::init error");
        return false;
    }
    for (int i=0; i<100; ++i)
        cli.do_query("http://sdk.test4.g.uc.cn/ss", NULL, [](int http_code, const std::string& data){
            printf("http:%d body:%s\n", http_code, data.c_str());
        });
    while (true) {
        cli.update();
        usleep(100000);
    }

    cli.destroy();

    return true;
}

bool test_http_client3() {
    http_client3 cli;

    if (!cli.init()) {
        perror("http_client2::init error");
        return false;
    }
    // http://sdk.test4.g.uc.cn/ss
    // https://openapi.360.cn/user/me.json
    for (int i=0; i<100; ++i)
        cli.do_query("https://openapi.360.cn/user/me.json", NULL, [](int http_code, const std::string& data){
            printf("http:%d body:%s\n", http_code, data.c_str());
        });
    while (true) {
        cli.update();
        usleep(100000);
    }

    cli.destroy();

    return true;
}
